import { Rule, Tree, noop } from '@angular-devkit/schematics';
import { Schema } from './schema';

import {
  getProjectFromWorkspace,
  getProjectTargetOptions,
} from '@angular/cdk/schematics';
import {
  getWorkspace,
  updateWorkspace,
} from '@schematics/angular/utility/workspace';
import { normalize } from '@angular-devkit/core';
import { join } from 'path';
import { existsSync } from 'fs';

const styleLessContent = `@import './theme.less';`;
const themeLessContent = `@import '../node_modules/ng-zorro-antd/ng-zorro-antd.less';
@import '../node_modules/joy-abpui-angular/style/joy-abpui-angular.less';
@import '../node_modules/joy-abpui-angular/style/preloader.less';
`;

export function createLessFiles(options: Schema): Rule {
  return async (host: Tree) => {
    const workspace = await getWorkspace(host);
    const project = getProjectFromWorkspace(workspace, options.project);

    if (project.sourceRoot) {
      const stylePath = normalize(join(project.sourceRoot, 'style.less'));
      if (existsSync(stylePath)) {
        host.overwrite(stylePath, styleLessContent);
      } else {
        host.create(stylePath, styleLessContent);
      }

      const themePath = normalize(join(project.sourceRoot, 'theme.less'));
      if (existsSync(themePath)) {
        host.overwrite(themePath, themeLessContent);
      } else {
        host.create(themePath, themeLessContent);
      }

      const oldStylePath = normalize(join(project.sourceRoot, 'styles.scss'));
      if (existsSync(themePath)) {
        host.delete(oldStylePath);
      }
    }

    return noop();
  };
}

export function updateStyleConfig(options: Schema): Rule {
  return updateWorkspace((workspace) => {
    const project = getProjectFromWorkspace(workspace, options.project);
    const targetOptions = getProjectTargetOptions(project, 'build');
    targetOptions.styles = ['src/style.less'];
    targetOptions.inlineStyleLanguage = 'less';

    const testOptions = getProjectTargetOptions(project, 'test');
    testOptions.styles = ['src/style.less'];
    testOptions.inlineStyleLanguage = 'less';

    project.extensions['schematics'] = {
      '@schematics/angular:component': {
        style: 'less',
      },
    };
  });
}
